﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using ListenMusic.Controllers;
using ListenMusic.User_Song_ServiceReference;
using ListenMusic.Models.Reposistory.User;
using ListenMusic.Models.Reposistory.Public;
using System.ServiceModel;
using System.Transactions;
using ListenMusic.Singer_ServiceReference;
using ListenMusic.Musician_ServiceReference;



using System.Drawing.Imaging;
using System.Drawing;

namespace ListenMusic.Controllers.User
{
    public class UploadController : ApplicationController
    {
        //
        // GET: /Upload/
        const long MAX_LENGTH = 4000000;
        public UploadController()
        {
               
        }
       
        public ActionResult Index() 
        {
            //createThumnails();
            ViewBag.allCategory = _category.getAllCategory();
            ViewBag.allCountry = _country.getAllCountry();          
            return View("UploadSong");
        }      
        [HttpPost]
        [Authorize(Roles = "websiteuser")]
        public ActionResult uploadfile(HttpPostedFileBase file, string songname, string musicianname, string singername, int cbxcountry, int cbxcategory)
        {
            try
            {
                if (file != null && file.ContentLength > 0)
                {
                        using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required))
                        {
                            try
                            {
                                string[] array_info_user = (string[])Session["user"];
                                string songurl = Path.GetFileName(file.FileName).ToLower().Replace(" ", "-");
                                string fileName = _upload.RandomStr() + "-" + songurl;
                                string extension = Path.GetExtension(file.FileName);
                                string[] ex_audio = new string[] { ".wma",".mp3"};
                                string[] ex_video = new string[] {".mp4",".wmv",".flv",".avi",".mpeg",".mpg"};
                                List<string> lst_ex_video = new List<string>(); 
                                List<string> lst_ex_audio = new List<string>();
                                lst_ex_video.AddRange(ex_video);
                                lst_ex_audio.AddRange(ex_audio);
                                string path = "";
                                ListenMusic.User_Song_ServiceReference.Song s = new ListenMusic.User_Song_ServiceReference.Song();
                                s.SongName = songname;
                                s.UserName = array_info_user[0];
                                s.SongURL =  fileName;
                                s.CountView = 0;
                                s.DateUp = DateTime.Now;
                                s.Active = false;
                                s.CategoryID = cbxcategory;
                                s.CountryID = Convert.ToInt16(cbxcountry);
                                s.Lyrics = null;
                                if (lst_ex_audio.IndexOf(extension) != -1)
                                {
                                    s.TypeID = 1;
                                    path = Path.Combine(Server.MapPath("~/Music/"), fileName);
                                }
                                if (lst_ex_video.IndexOf(extension) != -1)
                                {
                                    s.TypeID = 2;
                                    path = Path.Combine(Server.MapPath("~/Music/Videos/"), fileName);
                                   
                                }                              
                                if (singername == "")
                                {
                                    s.SingerID = 21;
                                }
                                else
                                {
                                    Singer singer = _singer.checkSingerName(singername);
                                    
                                    if (singer != null)
                                    {
                                        s.SingerID = singer.SingerID;
                                    }
                                    else
                                    {
                                        Singer newSinger = new Singer();
                                        newSinger.SingerName = singername;
                                        newSinger.Display = false;
                                        newSinger.CountryID = Convert.ToInt16(cbxcountry);
                                        newSinger.Picture = "noimage.gif";
                                        int newSingerID = _singer.getMaxID_Singer();
                                        bool rs = _singer.insertNewSinger(newSinger);
                                        if (rs)
                                        {
                                            s.SingerID = newSingerID + 1;
                                        }
                                        else
                                        {
                                            ts.Dispose();
                                        }
                                    }
                                }
                                if (musicianname == "")
                                {
                                    s.MusicianID = 35;
                                }
                                else
                                {
                                    Musician musician = _musician.checkMusicianName(musicianname);
                                    if (musician != null)
                                    {
                                        s.MusicianID = musician.MusicianID;
                                    }
                                    else
                                    {
                                        int newMusicianID = _musician.getMaxID_Musician();
                                        Musician newMusician = new Musician();
                                        newMusician.MusicianName = musicianname;                                        
                                        bool res = _musician.insertNewMusician(newMusician);
                                        if (res)
                                        {                                          
                                            s.MusicianID = newMusicianID + 1;
                                        }
                                        else
                                        {
                                            ts.Dispose();
                                        }
                                    }
                                }

                                bool result = _upload.uploadSong(s);
                                if (result)
                                {
                                    file.SaveAs(path);
                                    ts.Complete();
                                    ViewBag.messageSongName = songname;
                                    return RedirectToAction("UploadSuccess");
                                }
                            }
                            catch (Exception ex)
                            {
                                ts.Dispose();
                                throw ex;
                            }
                        }
                }
                return RedirectToAction("Index");
            }
            catch (FaultException ex)
            {
                throw ex;
            }
        }
        [Authorize(Roles = "websiteuser")]
        public ActionResult UploadSuccess()
        {
            return View();
        }
        //public void createThumnails()
        //{            
        //    string videoPath = Server.MapPath("~/Music/Videos/test.flv");
        //    string imagePath = Server.MapPath("~/Images/thumnailVideos/test.png");

        //    Bitmap bmp = FrameGrabber.GetFrameFromVideo(videoPath, 0.2d);
        //    bmp.Save(imagePath, ImageFormat.Png);
        //}
    }
}
